package com.heima.datasync.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.search.SearchConstants;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author by jojo
 * @Date 2022/3/15
 * @Description
 */
@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private EsService<SearchArticleVO> esService;
    @Override
    public ResponseResult dataInit() {
        //判断该索引库是否存在
        boolean isExist = esService.existIndex(SearchConstants.ARTICLE_INDEX_NAME);
        //存在，删除之前索引库
        if (isExist) {
            esService.deleteIndex(SearchConstants.ARTICLE_INDEX_NAME);
        }
        //创建新的索引库
        esService.createIndex(SearchConstants.ARTICLE_INDEX_PARAMS,SearchConstants.ARTICLE_INDEX_NAME);
        // 1. 从数据库中查询 文章的数据
        // 1.1  查询当前满足条件的文章总数量  count
        // 1.2  page(页数)   =  count / size  + 1
        // 1.3  for (int i=1     page   )       (page -1 ) * size    size
        List<ApArticle> articleList = apArticleMapper.findAllArticles();
        if (CollectionUtils.isEmpty(articleList)) {
            log.error("在数据库中没有文章数据");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"在数据库中没有文章数据！！！");
        }
        // 2. 使用es的批量处理api 批量插入数据到es
        List<SearchArticleVO> listVo = articleList.stream()
                .map(this::parseSearchArticleVO)
                .collect(Collectors.toList());
        //3.批量保存
        esService.saveBatch(listVo,SearchConstants.ARTICLE_INDEX_NAME);
        log.info("批量添加es成功！！！");
        return ResponseResult.okResult();
    }

    public SearchArticleVO parseSearchArticleVO(ApArticle apArticle){
        SearchArticleVO searchArticleVO = new SearchArticleVO();
        BeanUtils.copyProperties(apArticle,searchArticleVO);
        return searchArticleVO;
    }
}
